﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace NextDart
{
	public partial class Form1 : Form
	{
		SimpleParser m_parser = new SimpleParser();
		string m_title = "Next Dart";

		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
            lstDarts.Items.Clear();
            timer1_Tick(sender, e);
		}

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            TryPopulateFields();
            timer1.Enabled = true;
        }

        private void TryPopulateFields()
        {
            try
            {
                PopulateFields();
                lnkWebPage.Visible = false;
            }
            catch (WebException)
            {
                lblDescription.Text = "Failed to get web page. Click        to load in browser.";
                lnkWebPage.Visible = true;
            }
            catch (ApplicationException)
            {
                lblDescription.Text = "No darts listed";
            }
        }

		private void PopulateFields()
		{
			m_parser.Parse();

			lblDescription.Text = m_parser.Description;
            if (NextDartConfiguration.Instance.DiscardInterval > 0)
            {
                lblDescription.Text += string.Format("\r\n        [Discarding those sooner than {0} minutes]", NextDartConfiguration.Instance.DiscardInterval);
            }
			lblQueryTime.Text = string.Format("Last query at: {0:HH:mm}", m_parser.QueryTime);

			lstDarts.Items.Clear();
			foreach (DartDetails train in m_parser.NextDarts)
			{
				lstDarts.Items.Add(new ListViewItem(train.ToColumns()));
			}

			// sort out the form title
			m_title = "";
			foreach (DartDetails dart in m_parser.NextDarts)
			{
				m_title += string.Format("{0}, ", dart.DueIn);
			}
			if (m_parser.NextDarts.Count > 0)
			{
				m_title = m_title.Remove(m_title.Length - 2);
				m_title += string.Format(" minutes (from {0:HH:mm})", m_parser.QueryTime);
			}
			else
			{
				m_title = "Next Dart";
			}
			Text = m_title;
		}

        private void btnSettings_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            DialogResult result = new Settings().ShowDialog(this);
            if (result == DialogResult.OK)
                TryPopulateFields();

            timer1.Enabled = true;
        }

        private void lnkWebPage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(NextDartConfiguration.Instance.Link);
        }
	}
}
